package com.yusvn.scm.goods.base.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Inject;
import com.jfinal.ext.cors.EnableCORS;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.yusvn.scm.common.BaseController;
import com.yusvn.scm.common.kit.RetKit;
import com.yusvn.scm.common.model.ScmPzbhmx;
import com.yusvn.scm.goods.base.service.ScmPzbhService;
import com.yusvn.scm.goods.base.service.ScmPzbhmxService;

import java.util.List;

@EnableCORS
public class ScmPzbhmxController extends BaseController {

    @Inject
    ScmPzbhmxService srv;
    @Inject
    ScmPzbhService mxSrv;

    public void page(){
        Page<ScmPzbhmx> list = srv.selectPzbhList(getKv());

        renderJson(RetKit.ok().setCount(list.getTotalRow()).setData( JSONObject.toJSON(list.getList()) ));
    }

    public void addPzbhmx(){

        renderJson(srv.addPzbhmx(getRawData()));

    }

        public void updatePzbhmx(){

        renderJson(srv.updatePzbhmx(getRawData()));

    }

    public void deletePzbhmx(){

        renderJson(srv.deletePzbhmx(getPara("id")));
    }

    public void deleteBatch(){
        renderJson(srv.deleteBatch(getRawData()));


    }

    public void download(){
        List<Record> records = srv.selectAll(getKv());
        String fileName = "配置补货明细.xlsx";
        String[][] headerAlias = { {"id","编号"}, {"pzmx1","配置明细1"}, {"pzmx2", "配置明细2"}
                ,{"pzmx3", "配置明细3"}, {"pzmx4", "配置明细4"},{"pzmx5", "配置明细5"}
                ,{"pzmx6", "配置明细6"}, {"createtime", "创建时间"}
                , {"remark", "备注"} };

        exportExcel(records,fileName,headerAlias);
        renderNull();
    }

    public void  importExcel(){
        getFile();
        UploadFile file = null;
        String mid = getPara("mid");
        try {
            file = getFile();
            if (file == null) {
                renderJson(RetKit.fail("msg", "请先选择上传文件"));
                return;
            }
            // 表名
            String tableName = "scm_pzbhmx";
            RetKit retKit = importExcel(file,tableName,mid);
            renderJson(retKit);
        } catch (Exception e) {
            if (e instanceof com.jfinal.upload.ExceededSizeException) {
                renderJson(RetKit.fail("msg", "文件大小超出范围"));
            } else {
                if (file != null) {
                    // 只有出现异常时才能删除，不能在 finally 中删，因为后面需要用到上传文件
                    file.getFile().delete();
                }
                renderJson(RetKit.fail("msg", e.getMessage()));
            }
            return ;
        }


    }
}
